import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
import { getUserInfo } from '@/api/user'
import { getCateList } from '@/api/home'
import {getUploadToken,uploadQiniu} from '@/api/api';
import { Toast } from 'vant';

export default new Vuex.Store({
//  放数据的
  state: {
    uid:'',
    token:'',
    userInfo:{},
    isLogin:false,
    cate:[],
    liked_num:0,
    publish_num:0

  },
  getters: {
  },
  mutations: {
    change(state,val){
      state.a = val
    },
    change(state,{key,value}){
      state[key] = value
    },
    //退出登录需要 清空数据
    clear(state){
      state.uid='',
      state.token='',
      state.userInfo='',
      state.isLogin=false,
      state.publish_num=0,
      state.liked_num=0

    }
  },
  //调用方法
  actions: {
    getUserInfo({commit},token){
      getUserInfo({
        token
      }).then(res=>{
        console.log(res)
        
          commit('change',{key:"userInfo",value:res.userInfo})
          commit('change',{key:"uid",value:res.uid})
          commit('change',{key:"token",value:res.token})
          commit('change',{key:"isLogin",value:true})
          commit('change',{key:"publish_num",value:res.publish_num})
          commit('change',{key:"liked_num",value:res.liked_num})
        
        
       
      })
      
    },
    getCate({state,commit}){
      getCateList().then(res=>{
        commit('change',{key:'cate',value:res.data})
      })
    },
     //上传图片
     async upload(o,fileList){
      //1、判断有没有上传图片
      let imageSrc =[]
      if(!fileList ||!Array.isArray(fileList) || fileList.length === 0){
          //没有图片
          return imageSrc
      }
          //多图上传  多个异步任务同时执行的操作 
          //需要循环 可以用 promise  
          // promise  多个异步都执行完成 返回他们完成的后果
      let task = fileList.map(v=>{
          
          return new Promise(async(resolve,rejects)=>{
              let{file} = v;
              let { type } = file;
                  //  拿到类型  比如jpg
                  type = type.split('/')[1];  
                  // 重新命名
                  let file_name = `${new Date().getTime()}_${Math.random()
                  .toString(36)
                  .slice(2)}.${type}`;
              //去服务器中申请一个token
              let { token } = await getUploadToken();
              const formdata = new FormData();
              formdata.append('file', file);
              formdata.append('token', token);
              formdata.append('key', file_name);
          uploadQiniu(formdata).then(res=>{
              console.log(res)
              resolve(`http://toutiao.longxiaokj.com/` + res.key)   
          })
          })
         }) 
      // task [promises,promise]
          imageSrc = await Promise.all(task);
          return imageSrc
  },

  },
  modules: {
  }
})
